/*
 * Created on 6 oct. 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.console.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import fr.jade.console.core.AbstractCommand;
import fr.jade.console.core.Command;
import fr.jade.console.core.Environment;
import fr.jade.console.core.JTerm;

/**
 * @author ssicard

 */
public class Source extends AbstractCommand implements Command{

  public String getDescription(){
    return "execute a JTerm script file";
  }
  
  public String getHelp(){
    return "source <script file name>";
  }
  
  public String getName() {
    return "source";
  }
  
	public Object execute (String[] args, Environment env) throws Throwable {
		JTerm sh = (JTerm)env.getEnvVar("shell");
		try{
		  File sourceFile = new File(args[1]);
		  InputStream is = null;
		  if(sourceFile.exists()){
		     is = new FileInputStream(sourceFile);
		  }else{
		    is = getClass().getResourceAsStream("/"+args[1]);
		  }
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			String cmdLine;
			while( (cmdLine = in.readLine()) != null){
				System.out.println(cmdLine);
				sh.evaluateCmd(cmdLine);
			}
		}catch(IOException e){
			System.out.println("Load # Eror while reading "+ args[1]);
		}
		return null;
	}
}
